package com.wechatapp.mengyao.poetry.controller;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author yanghuaxu
 * @date 2025/5/18 9:56
 */
@Aspect
@Component
public class ControllerLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ControllerLogAspect.class);

    private static final int LOG_MAX_LENGTH = 5000;

    // 定义切入点：所有 Controller 层的方法
    @Around("execution(* com.wechatapp.mengyao.poetry.controller..*.*(..))")
    public Object logController(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String requestParamString = Arrays.toString(joinPoint.getArgs());
        // 记录请求信息
        logger.info("===== 请求开始 =====");
        logger.info("请求 URL: {}", request.getRequestURL());
        logger.info("请求方法: {}", request.getMethod());
        logger.info("请求参数: {}", requestParamString.substring(0, Math.min(LOG_MAX_LENGTH, requestParamString.length())));
        logger.info("请求 IP: {}", request.getRemoteAddr());

        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed(); // 执行目标方法
        long timeTaken = System.currentTimeMillis() - startTime;

        // 记录响应信息
        logger.info("===== 响应结果 =====");
        logger.info("响应状态: 200");
        logger.info("响应时间: {} ms", timeTaken);
        logger.info("===== 请求结束 =====");

        return result;
    }
}